package JUC;

/**
 * @author 豆包LU
 * @date 2023/5/6 14:11
 */
import java.util.concurrent.atomic.AtomicInteger;

import java.util.concurrent.atomic.AtomicInteger;

public class AtomicIntegerExample {
    public static void main(String[] args) {
        // 创建AtomicInteger对象，初始值为0
        AtomicInteger counter = new AtomicInteger(0);

        // 新建10个线程，每个线程对counter进行100次加操作
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                for (int j = 0; j < 100; j++) {
                    // 使用compareAndSet方法实现原子性的加操作
                    int oldValue, newValue;
                    do {
                        oldValue = counter.get();
                        newValue = oldValue + 1;
                    } while (!counter.compareAndSet(oldValue, newValue));
                }
            }).start();
        }

        // 等待所有线程执行完毕
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 输出counter的最终值
        System.out.println(counter.get());
    }
}

